<script>
import commonList from '../components/commonList'
import leftTreeLayout from '../components/leftTreeLayout'
import { PageTypes, ErrorCodes } from '../common/const';
import { getMemberConfig, memberBatchMove } from '../common/api';
import OnlyOneNodeSelectPerson from 'party_fe_component/src/components/tree/orgTree/onlyOneNodeSelectPerson';
import OrgTreeDialog from 'party_fe_component/src/components/tree/orgTree/orgTreeDialog';

export default {
    extends: commonList,
    mixins: [require('../common/orgTagMixin').default],
    data() {
        return {
            mappingFields: {
                department: "department_name"
            },
            isSearchData: false
        }
    },
    methods: {
        // 根据appId加载formName
        loadFormName() {
            return getMemberConfig().then(({ data = {} } = {}) => {
                const { formName, orgLabel = [] } = data;
                this.orgLabel = orgLabel[0] || '';
                this.formName = formName;
            })
        },
        loadListBy(page, searchData, isSearch) {
            this.loading = true
            var { searchGroupType, ...data } = searchData || {}
            this.isSearchData = Object.values(searchData || []).join('')
            var pars = {
                data,
                groupId: this.parentId,
                searchGroupType,
            }

            if (!isSearch) {
                pars.page = page;
            }

            return this.$x.post('/userinfo/op/query', pars, { maskOptions: false })
                .then(({ data = [], page } = {}) => {
                    this.dataList = data;

                    if (page) {
                        this.pageInfo = page;
                    }

                    this.total = page && page.total;
                })
                .finally(t => {
                    this.loading = false
                })
        },
        addItem() {
            if (this.uiSet.memberAddType === 'Others') {
                this.addItemFromDialog()
            } else {
                this.goEditRoute('/member/add', PageTypes.FormAdd)
            }
        },
        _rowEdit(row) {
            this.goEditRoute('/member/edit', PageTypes.FormEdit, row.id)
        },
        _rowView(row) {
            this.goEditRoute('/member/view', PageTypes.FormView, row.id)
        },
        // 移动操作
        _rowMove({ id }) {
            this.doBatchMove([ id ]);
        },
        doBatchMove(ids = []) {
            const { currentNodeId: origin } = this;
            this.$refs.moveDlg.showOrgDialog().then((selects) => {
                const target = selects[0].id;

                const hasSame = origin === target;
                if (hasSame) {
                    return this.$x.toast.warning('移动节点和选择节点相同，请重新选择');
                }

                this.loading = true;
                memberBatchMove(ids, origin, target).then(({ errcode = ErrorCodes.Success, errmsg = '操作成功' }) => {
                    this.loading = false;
                    if (errcode === ErrorCodes.Success) {
                        this.$x.toast.success(errmsg);
                        this.loadList();
                        this.reloadSubs();
                    } else {
                        this.$x.toast.error(errmsg);
                    }
                }).catch(() => {
                    this.loading = false;
                    this.$x.noop();
                });
            });
        },
        goEditRoute(path, pageType, id) {
            const { labelIds } = this;
            var pars = {
                pageType,
                formName: this.formName,
                parentId: this.parentId,
                parentName: this.parentOrg.name,
                orgLabel: labelIds && labelIds.length && labelIds[0]
            }
            if (id) pars.id = id
            this.$router.push(this.$x.toQueryUrl(path, pars))
        },
        _rowSetTop(row) {
            this.callSetTop(true, row)
        },
        _rowCancelTop(row) {
            this.callSetTop(false, row)
        },
        callSetTop(isTop, row) {
            var pars = {
                isTop: isTop ? 1 : 0,
                id: row.id,
                partyOrganization: [this.parentId],
                spId: this.$x.tokenUtil.spId,
                businessType: this.$x.tokenUtil.businessType,
            }
            this.$x.post('/org/party-member/top', pars)
                .then(res => {
                    this.$x.toast.success('操作成功')
                    this.loadList()
                })
        },
        // 批量移动
        _batBatMove(rows) {
            this.doBatchMove(rows.map(row => row.id));
        },
        _batBatDelete(rows) {
            /* eslint-disable-next-line */
            var h = this.$createElement
            var msg = this.fgTexts.confirmDelete || '请确定是否删除' + this.fgObjTitle + '？'
            this.$x.confirm(msg, '删除' + this.fgObjTitle, {
                confirmButtonText: this.fgTexts.delete || '删除',
                cancelButtonText: this.fgTexts.cancel || '取消',
                type: 'warning',
            }).then(async t => {
                var pars = {
                    addType: this.uiSet.memberAddType === 'Input' ? 1 : 2, //1录入2筛选
                    parent_group_id: this.parentId,
                    idList: rows.map(row => row.id)
                }
                await this.$x.post('/userinfo/op/del', pars)
                this.$x.toast.success(this.fgTexts.deleteSuccess || '删除成功')
                this.loadList()
            }).catch(this.$x.noop)
        },
        getRowActions(row) {
            return this.uiSet.rowActions.map(action => {
                // 已置顶，置顶按钮变为取消置顶
                if (action === 'SetTop') {
                    //搜索时不能置顶
                    if (this.isSearchData) return
                    if (row.isTop) {
                        action = 'CancelTop'
                    }
                }
                return action
            }).filter(a => a)
        },

        async addItemFromDialog() {
            const { currentNodeId } = this;

            if (!currentNodeId) {
                return this.$x.toast.error('请先创建组织，再添加人员');
            }

            var getParentOrg = async (curOrgId) => {
                var pars = {
                    businessType: this.$x.tokenUtil.businessType,
                    id: curOrgId,
                    spId: this.$x.tokenUtil.spId,
                }
                var res = await this.$x.post('/org/org/v2/get-group-detail', pars, { maskOptions: true })
                var orgData = res.data || []
                if (!orgData.parentId || orgData.parentId == -1) {
                    return null
                }
                // 直到找到父级依赖组织为止
                if ((orgData.labelIdList || []).find(labelId => labelId && labelId == this.uiSet.dependParentTag)) {
                    return orgData
                }
                return getParentOrg(orgData.parentId)
            }
            // var parentData = await getParentOrg(this.rootOrg.id)
            var parentData = await getParentOrg(currentNodeId);
            if (!parentData) {
                return this.$x.toast.error('未找到父级单位');
            }
            //弹出框选人
            var currentOrg = {
                isOrg: true,
                icon: '',
                configedWhiteList: false,
                id: parentData.id,
                memberId: null,
                name: parentData.name,
                parentGroup: null,
                parentId: '0',
                permission: true,
                subGroups: null,
                childNodes: [],
                view: false
            }

            this.$refs.addMemberDlg.showOrgDialog([currentOrg], [])
                .then(async selected => {
                    const callNext = index => {
                        var { id, sex, name, mobile, } = selected[index] || {}
                        var data = {
                            id,
                            sex,
                            name,
                            telephone: mobile,
                            group_id: this.parentId,
                        }
                        this.$x.post('/userinfo/op/save', { data }, { maskOptions: true }).then(() => {
                            if (index + 1 < selected.length) {
                                callNext(index + 1)
                            } else {
                                this.$x.toast.success('新增成功！');
                                this.loadList()
                            }
                        });
                    }
                    callNext(0)
                })
                .catch(this.$x.noop);
        },
        _batExport() {
            var pars = {
                groupId: this.parentId,
            }
            this.$x.post('/userinfo/file/excelExport', pars).then(res => {
                this.showImExportMsg(false)
            })
        },
        _batImport() {
            var pars = {
                rootId: this.rootId,
                parentId: this.parentId,
                formName: this.formName,
                objTitle: this.fgObjTitle,
            }
            this.$router.push(this.$x.toQueryUrl('/member/import', pars))
        },
    },
    render(h) {
        if (this.uiSet) {
            // 父组件模板渲染
            var superRendered = this.$options.extends.render.apply(this, arguments)
            var addMemberDialog = (
                <OnlyOneNodeSelectPerson
                    ref="addMemberDlg"
                    show-member={true}
                    checkType="member"
                    tipText={ this.uiSet.memberAddTip }
                    bizAppId={this.$x.tokenUtil.appId}
                    labelIdList={this.uiSet.addMemberTag ? String(this.uiSet.addMemberTag).split(';') : []}
                    orgPerson={'' + this.uiSet.memberTag}
                    searchText={'人员'}
                    onlyLoadPerson={true}
                >
                </OnlyOneNodeSelectPerson>)

            var moveDialog = (
                <OrgTreeDialog
                    ref="moveDlg"
                    enableIdList={ [ this.orgLabel ] }
                    singleCheck={true}
                    permission={true}>
                </OrgTreeDialog>
            );

            return (
                <leftTreeLayout
                    hideLeft={this.isSubRouter}
                    onNodeClick={this.onNodeClick}
                    fgTexts={this.fgTexts}
                    onRootChanged={this.changeRoot}
                    selectedRoot={this.uiSet.dependOn === 'Double'}
                    orgTags={[this.uiSet.dependOrgTag]}
                    switchOrg={this.uiSet.dependOn === 'Double'}
                    dependOrgTags={this.uiSet.dependOn === 'Double' ? [this.uiSet.dependOrgTag] : []}
                >
                    <header slot="treeHead" class="tree-head">{this.fgTexts.memberStruct || '组织架构'}</header>
                    {superRendered}{addMemberDialog}{moveDialog}
                </leftTreeLayout>
            )
        }
        return <div/>
    },
    computed: {
        // dependOrgTags() {
        //     return [this.uiSet.dependOrgTag, this.uiSet.dependParentTag].filter(tag => tag)
        // },
        showActionAdd () {
            return true;
        },
        isSubRouter() {
            return this.$route.path !== '/member/list'
        },
        fgObjTitle() {
            return this.fgTagNames[this.uiSet && this.uiSet.memberTag] || '人员'
        },
    }
}
</script>
